package com.jdyinfo.ic.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.juli.logging.LogFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@MapperScan(basePackages="com.jdyinfo.ic.mysql.mapper", sqlSessionFactoryRef="sqlSessionFactory")
public class MyBatisMySQLConfig {
	@Autowired
	MySQLSettings mysqlSettings;
	
	Logger logger = LoggerFactory.getLogger(MyBatisMySQLConfig.class);
	
	@Bean(name = "dataSource", destroyMethod = "close")
	public DataSource dataSource(){
	    HikariConfig hikariConfig = new HikariConfig();
	    logger.info(mysqlSettings.getDriverClassName());
	    logger.info(mysqlSettings.getUrl());
	    hikariConfig.setDriverClassName(mysqlSettings.getDriverClassName());
	    hikariConfig.setJdbcUrl(mysqlSettings.getUrl()); 
	    hikariConfig.setUsername(mysqlSettings.getUsername());
	    hikariConfig.setPassword(mysqlSettings.getPassword());

	    hikariConfig.setMaximumPoolSize(5);
	    hikariConfig.setConnectionTestQuery("SELECT 1");
	    hikariConfig.setPoolName("springHikariCP");

	    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
	    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
	    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
	    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

	    HikariDataSource dataSource = new HikariDataSource(hikariConfig);

	    return dataSource;
	}
	
	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception{
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		sessionFactory.setTypeAliasesPackage("com.jdyinfo.ic.mysql.entity");
		
		return sessionFactory.getObject();
	}
	
}
